package com.breaktian.assemble.webview;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.breaktian.assemble.R;
import com.breaktian.assemble.utils.ViewUtil;

/**
 * Created by tiankeke on 2017/5/31.
 * 带进度的webview
 */
public class ProgressWebView extends BaseWebView {
    private Context mContext;
    private ProgressBar progressBar;

    public ProgressWebView(Context context) {
        super(context);
        this.mContext = context;
        initProgressWebView();
    }

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initProgressWebView();
    }

    public ProgressWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initProgressWebView();
    }

    private void initProgressWebView() {
        progressBar = (ProgressBar) LayoutInflater.from(mContext).inflate(R.layout.bm_layout_progress,null);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewUtil.dip2px(mContext,3), 0, -1);
        progressBar.setLayoutParams(params);
        addView(progressBar);

        setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                progressBar.setProgress(newProgress);
                if(newProgress==100){
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(GONE);
                        }
                    },1000);

                }
                else{
                    progressBar.setVisibility(VISIBLE);
                }


            }
        });


        setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }
        });


    }


}
